#include "CollectorConfigDialog.h"
#include "utils/CsvHelper.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QGroupBox>
#include <QHeaderView>
#include <QMessageBox>
#include <QLabel>
#include <QDialogButtonBox>
#include <QJsonArray>
#include <QFileDialog>
#include <QSplitter>
#include <QScrollArea>
#include <QDebug>
#include <QMenu>
#include <QAction>

namespace ModbusPlexLink {

CollectorConfigDialog::CollectorConfigDialog(const QJsonObject& config, QWidget *parent)
    : QDialog(parent)
    , m_isNewCollector(config.isEmpty())
    , m_originalConfig(config)
    , m_nameEdit(nullptr)
    , m_ipEdit(nullptr)
    , m_portSpin(nullptr)
    , m_unitIdSpin(nullptr)
    , m_pollRateSpin(nullptr)
    , m_timeoutSpin(nullptr)
    , m_maxRetriesSpin(nullptr)
    , m_autoReconnectCheck(nullptr)
    , m_logErrorsCheck(nullptr)
    , m_mappingTable(nullptr)
    , m_addMappingBtn(nullptr)
    , m_deleteMappingBtn(nullptr)
    , m_duplicateMappingBtn(nullptr)
    , m_importCsvBtn(nullptr)
    , m_exportCsvBtn(nullptr)
    , m_isUpdatingTable(false)
{
    setWindowTitle(m_isNewCollector ? tr("新建采集器") : tr("编辑采集器"));
    resize(1200, 700);
    setMinimumSize(1000, 600);
    
    setupUi();
    loadConfig();
}

CollectorConfigDialog::~CollectorConfigDialog() {
}

void CollectorConfigDialog::setupUi() {
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(15, 15, 15, 15);
    mainLayout->setSpacing(15);
    
    // 使用分割器分隔基本信息和映射表格
    QSplitter* splitter = new QSplitter(Qt::Vertical, this);
    
    // 基本信息区域
    QWidget* basicInfoWidget = createBasicInfoSection();
    splitter->addWidget(basicInfoWidget);
    
    // 映射表格区域
    QWidget* mappingWidget = createMappingTableSection();
    splitter->addWidget(mappingWidget);
    
    splitter->setStretchFactor(0, 2);
    splitter->setStretchFactor(1, 5);
    
    mainLayout->addWidget(splitter);
    
    // 底部按钮
    QDialogButtonBox* buttonBox = new QDialogButtonBox(
        QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
    
    connect(buttonBox, &QDialogButtonBox::accepted, this, &CollectorConfigDialog::onAccepted);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &CollectorConfigDialog::onRejected);
    
    mainLayout->addWidget(buttonBox);
}

QWidget* CollectorConfigDialog::createBasicInfoSection() {
    QGroupBox* groupBox = new QGroupBox(tr("采集器基本信息"));
    QFormLayout* formLayout = new QFormLayout(groupBox);
    formLayout->setLabelAlignment(Qt::AlignRight | Qt::AlignVCenter);
    formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
    
    // 名称
    m_nameEdit = new QLineEdit();
    m_nameEdit->setPlaceholderText(tr("例如: MeterGroup_Collector"));
    connect(m_nameEdit, &QLineEdit::textChanged, this, &CollectorConfigDialog::onNameChanged);
    formLayout->addRow(tr("名称*:"), m_nameEdit);
    
    // IP地址
    m_ipEdit = new QLineEdit();
    m_ipEdit->setPlaceholderText(tr("例如: 192.168.1.10"));
    connect(m_ipEdit, &QLineEdit::textChanged, this, &CollectorConfigDialog::onIpChanged);
    formLayout->addRow(tr("IP地址*:"), m_ipEdit);
    
    // 端口和从站ID在同一行
    QHBoxLayout* portUnitLayout = new QHBoxLayout();
    
    m_portSpin = new QSpinBox();
    m_portSpin->setRange(1, 65535);
    m_portSpin->setValue(502);
    m_portSpin->setMinimumWidth(100);
    
    m_unitIdSpin = new QSpinBox();
    m_unitIdSpin->setRange(0, 255);
    m_unitIdSpin->setValue(1);
    m_unitIdSpin->setMinimumWidth(100);
    
    portUnitLayout->addWidget(new QLabel(tr("端口:")));
    portUnitLayout->addWidget(m_portSpin);
    portUnitLayout->addSpacing(20);
    portUnitLayout->addWidget(new QLabel(tr("从站ID:")));
    portUnitLayout->addWidget(m_unitIdSpin);
    portUnitLayout->addStretch();
    
    formLayout->addRow(tr("连接参数:"), portUnitLayout);
    
    // 轮询间隔、超时、重试在同一行
    QHBoxLayout* timingLayout = new QHBoxLayout();
    
    m_pollRateSpin = new QSpinBox();
    m_pollRateSpin->setRange(100, 60000);
    m_pollRateSpin->setValue(1000);
    m_pollRateSpin->setSuffix(tr(" ms"));
    m_pollRateSpin->setMinimumWidth(120);
    
    m_timeoutSpin = new QSpinBox();
    m_timeoutSpin->setRange(100, 10000);
    m_timeoutSpin->setValue(3000);
    m_timeoutSpin->setSuffix(tr(" ms"));
    m_timeoutSpin->setMinimumWidth(120);
    
    m_maxRetriesSpin = new QSpinBox();
    m_maxRetriesSpin->setRange(0, 10);
    m_maxRetriesSpin->setValue(3);
    m_maxRetriesSpin->setMinimumWidth(100);
    
    timingLayout->addWidget(new QLabel(tr("轮询间隔:")));
    timingLayout->addWidget(m_pollRateSpin);
    timingLayout->addSpacing(10);
    timingLayout->addWidget(new QLabel(tr("超时:")));
    timingLayout->addWidget(m_timeoutSpin);
    timingLayout->addSpacing(10);
    timingLayout->addWidget(new QLabel(tr("重试次数:")));
    timingLayout->addWidget(m_maxRetriesSpin);
    timingLayout->addStretch();
    
    formLayout->addRow(tr("时序参数:"), timingLayout);
    
    // 选项
    QHBoxLayout* optionsLayout = new QHBoxLayout();
    
    m_autoReconnectCheck = new QCheckBox(tr("自动重连"));
    m_autoReconnectCheck->setChecked(true);
    
    m_logErrorsCheck = new QCheckBox(tr("记录错误日志"));
    m_logErrorsCheck->setChecked(true);
    
    optionsLayout->addWidget(m_autoReconnectCheck);
    optionsLayout->addWidget(m_logErrorsCheck);
    optionsLayout->addStretch();
    
    formLayout->addRow(tr("选项:"), optionsLayout);
    
    return groupBox;
}

QWidget* CollectorConfigDialog::createMappingTableSection() {
    QWidget* container = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(container);
    
    // 标题
    QHBoxLayout* headerLayout = new QHBoxLayout();
    
    QLabel* titleLabel = new QLabel(tr("采集器映射规则"));
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(11);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    headerLayout->addWidget(titleLabel);
    
    headerLayout->addStretch();
    
    QLabel* countLabel = new QLabel(tr("映射数量: 0"));
    countLabel->setObjectName("mappingCountLabel");
    countLabel->setStyleSheet("color: #666;");
    headerLayout->addWidget(countLabel);
    
    layout->addLayout(headerLayout);
    
    // 说明
    QLabel* hintLabel = new QLabel(
        tr("定义如何从物理设备读取数据并转换为UDM标签。双击单元格可编辑。"));
    hintLabel->setWordWrap(true);
    hintLabel->setStyleSheet("color: #666; padding: 5px;");
    layout->addWidget(hintLabel);
    
    // 映射表格
    m_mappingTable = new QTableWidget();
    m_mappingTable->setColumnCount(11);
    m_mappingTable->setHorizontalHeaderLabels({
        tr("#"), tr("标签名*"), tr("注释"), tr("寄存器类型"), tr("地址"), 
        tr("数据类型"), tr("字节序"), tr("倍率"), tr("偏移"), 
        tr("单位"), tr("启用")
    });
    
    m_mappingTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_mappingTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_mappingTable->setAlternatingRowColors(true);
    m_mappingTable->verticalHeader()->setVisible(false);
    m_mappingTable->horizontalHeader()->setStretchLastSection(false);
    
    // 设置列宽
    m_mappingTable->setColumnWidth(0, 40);   // 行号
    m_mappingTable->setColumnWidth(1, 150);  // 标签名
    m_mappingTable->setColumnWidth(2, 120);  // 注释
    m_mappingTable->setColumnWidth(3, 100);  // 寄存器类型
    m_mappingTable->setColumnWidth(4, 80);   // 地址
    m_mappingTable->setColumnWidth(5, 100);  // 数据类型
    m_mappingTable->setColumnWidth(6, 80);   // 字节序
    m_mappingTable->setColumnWidth(7, 70);   // 倍率
    m_mappingTable->setColumnWidth(8, 70);   // 偏移
    m_mappingTable->setColumnWidth(9, 60);   // 单位
    m_mappingTable->setColumnWidth(10, 60);  // 启用
    
    connect(m_mappingTable, &QTableWidget::itemSelectionChanged,
            this, &CollectorConfigDialog::onMappingTableSelectionChanged);
    connect(m_mappingTable, &QTableWidget::cellChanged,
            this, &CollectorConfigDialog::onMappingTableCellChanged);
    
    layout->addWidget(m_mappingTable);
    
    // 操作按钮
    QHBoxLayout* btnLayout = new QHBoxLayout();
    
    m_addMappingBtn = new QPushButton(tr("添加"));
    m_deleteMappingBtn = new QPushButton(tr("删除"));
    m_duplicateMappingBtn = new QPushButton(tr("复制"));
    m_importCsvBtn = new QPushButton(tr("从CSV导入..."));
    m_exportCsvBtn = new QPushButton(tr("导出到CSV..."));
    
    connect(m_addMappingBtn, &QPushButton::clicked, this, &CollectorConfigDialog::onAddMapping);
    connect(m_deleteMappingBtn, &QPushButton::clicked, this, &CollectorConfigDialog::onDeleteMapping);
    connect(m_duplicateMappingBtn, &QPushButton::clicked, this, &CollectorConfigDialog::onDuplicateMapping);
    connect(m_importCsvBtn, &QPushButton::clicked, this, &CollectorConfigDialog::onImportFromCSV);
    connect(m_exportCsvBtn, &QPushButton::clicked, this, &CollectorConfigDialog::onExportToCSV);
    
    btnLayout->addWidget(m_addMappingBtn);
    btnLayout->addWidget(m_deleteMappingBtn);
    btnLayout->addWidget(m_duplicateMappingBtn);
    btnLayout->addSpacing(20);
    btnLayout->addWidget(m_importCsvBtn);
    btnLayout->addWidget(m_exportCsvBtn);
    btnLayout->addStretch();
    
    layout->addLayout(btnLayout);
    
    updateMappingButtons();
    
    return container;
}

void CollectorConfigDialog::loadConfig() {
    if (m_isNewCollector) {
        // 新建采集器，使用默认值
        m_nameEdit->setText(tr("新采集器"));
        m_nameEdit->selectAll();
        m_nameEdit->setFocus();
        return;
    }
    
    // 加载基本信息
    m_nameEdit->setText(m_originalConfig.value("name").toString());
    m_ipEdit->setText(m_originalConfig.value("ip").toString());
    m_portSpin->setValue(m_originalConfig.value("port").toInt(502));
    m_unitIdSpin->setValue(m_originalConfig.value("unitId").toInt(1));
    m_pollRateSpin->setValue(m_originalConfig.value("pollRate").toInt(1000));
    m_timeoutSpin->setValue(m_originalConfig.value("timeout").toInt(3000));
    m_maxRetriesSpin->setValue(m_originalConfig.value("maxRetries").toInt(3));
    m_autoReconnectCheck->setChecked(m_originalConfig.value("autoReconnect").toBool(true));
    m_logErrorsCheck->setChecked(m_originalConfig.value("logErrors").toBool(true));
    
    // 加载映射规则
    m_mappings.clear();
    QJsonArray mappingsArray = m_originalConfig.value("mappings").toArray();
    
    for (const QJsonValue& value : mappingsArray) {
        if (!value.isObject()) continue;
        
        QJsonObject mappingObj = value.toObject();
        CollectorMappingRule rule;
        
        rule.tagName = mappingObj.value("tagName").toString();
        rule.comment = mappingObj.value("comment").toString();
        rule.registerType = DataTypeUtils::registerTypeFromString(
            mappingObj.value("registerType").toString("Holding"));
        rule.address = mappingObj.value("address").toInt(0);
        rule.count = mappingObj.value("count").toInt(0);
        rule.dataType = DataTypeUtils::dataTypeFromString(
            mappingObj.value("dataType").toString("UInt16"));
        rule.byteOrder = DataTypeUtils::byteOrderFromString(
            mappingObj.value("byteOrder").toString("AB"));
        rule.scale = mappingObj.value("scale").toDouble(1.0);
        rule.offset = mappingObj.value("offset").toDouble(0.0);
        rule.unit = mappingObj.value("unit").toString();
        rule.enabled = mappingObj.value("enabled").toBool(true);
        
        m_mappings.append(rule);
    }
    
    refreshMappingTable();
}

bool CollectorConfigDialog::validateConfig() {
    // 验证名称
    if (m_nameEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, tr("验证失败"), tr("采集器名称不能为空"));
        m_nameEdit->setFocus();
        return false;
    }
    
    // 验证IP地址
    QString ip = m_ipEdit->text().trimmed();
    if (ip.isEmpty()) {
        QMessageBox::warning(this, tr("验证失败"), tr("IP地址不能为空"));
        m_ipEdit->setFocus();
        return false;
    }
    
    // 验证映射规则
    for (int i = 0; i < m_mappings.size(); ++i) {
        const CollectorMappingRule& rule = m_mappings[i];
        if (rule.tagName.trimmed().isEmpty()) {
            QMessageBox::warning(this, tr("验证失败"), 
                tr("映射规则 #%1 的标签名不能为空").arg(i + 1));
            m_mappingTable->selectRow(i);
            return false;
        }
    }
    
    return true;
}

QJsonObject CollectorConfigDialog::getConfig() const {
    QJsonObject config;
    
    // 基本信息
    config["name"] = m_nameEdit->text().trimmed();
    config["protocol"] = "modbus-tcp";
    config["ip"] = m_ipEdit->text().trimmed();
    config["port"] = m_portSpin->value();
    config["unitId"] = m_unitIdSpin->value();
    config["pollRate"] = m_pollRateSpin->value();
    config["timeout"] = m_timeoutSpin->value();
    config["maxRetries"] = m_maxRetriesSpin->value();
    config["autoReconnect"] = m_autoReconnectCheck->isChecked();
    config["logErrors"] = m_logErrorsCheck->isChecked();
    
    // 映射规则
    QJsonArray mappingsArray;
    for (const CollectorMappingRule& rule : m_mappings) {
        QJsonObject mappingObj;
        mappingObj["tagName"] = rule.tagName;
        mappingObj["comment"] = rule.comment;
        mappingObj["registerType"] = DataTypeUtils::registerTypeToString(rule.registerType);
        mappingObj["address"] = rule.address;
        mappingObj["count"] = rule.count > 0 ? rule.count : DataTypeUtils::getRegisterCount(rule.dataType);
        mappingObj["dataType"] = DataTypeUtils::dataTypeToString(rule.dataType);
        mappingObj["byteOrder"] = DataTypeUtils::byteOrderToString(rule.byteOrder);
        mappingObj["scale"] = rule.scale;
        mappingObj["offset"] = rule.offset;
        mappingObj["unit"] = rule.unit;
        mappingObj["enabled"] = rule.enabled;
        
        mappingsArray.append(mappingObj);
    }
    config["mappings"] = mappingsArray;
    
    return config;
}

void CollectorConfigDialog::setConfig(const QJsonObject& config) {
    m_originalConfig = config;
    m_isNewCollector = false;
    loadConfig();
}

void CollectorConfigDialog::refreshMappingTable() {
    m_isUpdatingTable = true;
    
    m_mappingTable->setRowCount(0);
    m_mappingTable->setRowCount(m_mappings.size());
    
    for (int i = 0; i < m_mappings.size(); ++i) {
        setupMappingTableRow(i, m_mappings[i]);
    }
    
    // 更新计数标签
    QLabel* countLabel = findChild<QLabel*>("mappingCountLabel");
    if (countLabel) {
        countLabel->setText(tr("映射数量: %1").arg(m_mappings.size()));
    }
    
    m_isUpdatingTable = false;
    updateMappingButtons();
}

void CollectorConfigDialog::setupMappingTableRow(int row, const CollectorMappingRule& rule) {
    // 0: 行号（不可编辑）
    QTableWidgetItem* rowNumItem = new QTableWidgetItem(QString::number(row + 1));
    rowNumItem->setTextAlignment(Qt::AlignCenter);
    rowNumItem->setFlags(rowNumItem->flags() & ~Qt::ItemIsEditable);
    rowNumItem->setBackground(QBrush(QColor(240, 240, 240)));
    m_mappingTable->setItem(row, 0, rowNumItem);
    
    // 1: 标签名（可编辑文本）
    QTableWidgetItem* tagItem = new QTableWidgetItem(rule.tagName);
    m_mappingTable->setItem(row, 1, tagItem);
    
    // 2: 注释（可编辑文本）
    QTableWidgetItem* commentItem = new QTableWidgetItem(rule.comment);
    m_mappingTable->setItem(row, 2, commentItem);
    
    // 3: 寄存器类型（下拉框）- 使用功能码
    QComboBox* regTypeCombo = new QComboBox();
    regTypeCombo->addItem("01 (Coil)", static_cast<int>(RegisterType::Coil));
    regTypeCombo->addItem("02 (Discrete)", static_cast<int>(RegisterType::DiscreteInput));
    regTypeCombo->addItem("03 (Holding)", static_cast<int>(RegisterType::HoldingRegister));
    regTypeCombo->addItem("04 (Input)", static_cast<int>(RegisterType::InputRegister));
    
    // 根据枚举值设置当前项
    int currentTypeValue = static_cast<int>(rule.registerType);
    for (int i = 0; i < regTypeCombo->count(); ++i) {
        if (regTypeCombo->itemData(i).toInt() == currentTypeValue) {
            regTypeCombo->setCurrentIndex(i);
            break;
        }
    }
    m_mappingTable->setCellWidget(row, 3, regTypeCombo);
    
    // 4: 地址（可编辑数字）
    QTableWidgetItem* addrItem = new QTableWidgetItem(QString::number(rule.address));
    addrItem->setTextAlignment(Qt::AlignCenter);
    m_mappingTable->setItem(row, 4, addrItem);
    
    // 5: 数据类型（下拉框）
    QComboBox* dataTypeCombo = new QComboBox();
    dataTypeCombo->addItem("UInt16", static_cast<int>(DataType::UInt16));
    dataTypeCombo->addItem("Int16", static_cast<int>(DataType::Int16));
    dataTypeCombo->addItem("UInt32", static_cast<int>(DataType::UInt32));
    dataTypeCombo->addItem("Int32", static_cast<int>(DataType::Int32));
    dataTypeCombo->addItem("Float32", static_cast<int>(DataType::Float32));
    dataTypeCombo->addItem("UInt64", static_cast<int>(DataType::UInt64));
    dataTypeCombo->addItem("Int64", static_cast<int>(DataType::Int64));
    dataTypeCombo->addItem("Float64", static_cast<int>(DataType::Float64));
    
    // 根据枚举值设置当前项
    int currentDataTypeValue = static_cast<int>(rule.dataType);
    for (int i = 0; i < dataTypeCombo->count(); ++i) {
        if (dataTypeCombo->itemData(i).toInt() == currentDataTypeValue) {
            dataTypeCombo->setCurrentIndex(i);
            break;
        }
    }
    m_mappingTable->setCellWidget(row, 5, dataTypeCombo);
    
    // 6: 字节序（下拉框）
    QComboBox* byteOrderCombo = new QComboBox();
    byteOrderCombo->addItem("AB", static_cast<int>(ByteOrder::AB));
    byteOrderCombo->addItem("BA", static_cast<int>(ByteOrder::BA));
    byteOrderCombo->addItem("ABCD", static_cast<int>(ByteOrder::ABCD));
    byteOrderCombo->addItem("DCBA", static_cast<int>(ByteOrder::DCBA));
    byteOrderCombo->addItem("CDAB", static_cast<int>(ByteOrder::CDAB));
    byteOrderCombo->addItem("BADC", static_cast<int>(ByteOrder::BADC));
    
    // 根据枚举值设置当前项
    int currentByteOrderValue = static_cast<int>(rule.byteOrder);
    for (int i = 0; i < byteOrderCombo->count(); ++i) {
        if (byteOrderCombo->itemData(i).toInt() == currentByteOrderValue) {
            byteOrderCombo->setCurrentIndex(i);
            break;
        }
    }
    m_mappingTable->setCellWidget(row, 6, byteOrderCombo);
    
    // 7: 倍率（可编辑数字）
    QTableWidgetItem* scaleItem = new QTableWidgetItem(QString::number(rule.scale));
    scaleItem->setTextAlignment(Qt::AlignCenter);
    m_mappingTable->setItem(row, 7, scaleItem);
    
    // 8: 偏移（可编辑数字）
    QTableWidgetItem* offsetItem = new QTableWidgetItem(QString::number(rule.offset));
    offsetItem->setTextAlignment(Qt::AlignCenter);
    m_mappingTable->setItem(row, 8, offsetItem);
    
    // 9: 单位（可编辑文本）
    QTableWidgetItem* unitItem = new QTableWidgetItem(rule.unit);
    unitItem->setTextAlignment(Qt::AlignCenter);
    m_mappingTable->setItem(row, 9, unitItem);
    
    // 10: 启用（复选框）
    QCheckBox* enabledCheck = new QCheckBox();
    enabledCheck->setChecked(rule.enabled);
    QWidget* checkWidget = new QWidget();
    QHBoxLayout* checkLayout = new QHBoxLayout(checkWidget);
    checkLayout->addWidget(enabledCheck);
    checkLayout->setAlignment(Qt::AlignCenter);
    checkLayout->setContentsMargins(0, 0, 0, 0);
    m_mappingTable->setCellWidget(row, 10, checkWidget);
}

CollectorMappingRule CollectorConfigDialog::getMappingRuleFromRow(int row) const {
    CollectorMappingRule rule;
    
    // 跳过第0列（行号）
    
    // 标签名
    QTableWidgetItem* tagItem = m_mappingTable->item(row, 1);
    rule.tagName = tagItem ? tagItem->text() : "";
    
    // 注释
    QTableWidgetItem* commentItem = m_mappingTable->item(row, 2);
    rule.comment = commentItem ? commentItem->text() : "";
    
    // 寄存器类型
    QComboBox* regTypeCombo = qobject_cast<QComboBox*>(m_mappingTable->cellWidget(row, 3));
    rule.registerType = regTypeCombo ? 
        static_cast<RegisterType>(regTypeCombo->currentData().toInt()) : 
        RegisterType::HoldingRegister;
    
    // 地址
    QTableWidgetItem* addrItem = m_mappingTable->item(row, 4);
    rule.address = addrItem ? addrItem->text().toInt() : 0;
    
    // 数据类型
    QComboBox* dataTypeCombo = qobject_cast<QComboBox*>(m_mappingTable->cellWidget(row, 5));
    rule.dataType = dataTypeCombo ? 
        static_cast<DataType>(dataTypeCombo->currentData().toInt()) : 
        DataType::UInt16;
    
    // 字节序
    QComboBox* byteOrderCombo = qobject_cast<QComboBox*>(m_mappingTable->cellWidget(row, 6));
    rule.byteOrder = byteOrderCombo ? 
        static_cast<ByteOrder>(byteOrderCombo->currentData().toInt()) : 
        ByteOrder::AB;
    
    // 倍率
    QTableWidgetItem* scaleItem = m_mappingTable->item(row, 7);
    rule.scale = scaleItem ? scaleItem->text().toDouble() : 1.0;
    
    // 偏移
    QTableWidgetItem* offsetItem = m_mappingTable->item(row, 8);
    rule.offset = offsetItem ? offsetItem->text().toDouble() : 0.0;
    
    // 单位
    QTableWidgetItem* unitItem = m_mappingTable->item(row, 9);
    rule.unit = unitItem ? unitItem->text() : "";
    
    // 启用
    QWidget* checkWidget = m_mappingTable->cellWidget(row, 10);
    QCheckBox* enabledCheck = checkWidget ? checkWidget->findChild<QCheckBox*>() : nullptr;
    rule.enabled = enabledCheck ? enabledCheck->isChecked() : true;
    
    // 自动计算count
    rule.count = DataTypeUtils::getRegisterCount(rule.dataType);
    
    return rule;
}

void CollectorConfigDialog::updateMappingButtons() {
    bool hasSelection = m_mappingTable->currentRow() >= 0;
    bool hasRows = m_mappings.size() > 0;
    
    m_deleteMappingBtn->setEnabled(hasSelection);
    m_duplicateMappingBtn->setEnabled(hasSelection);
    m_exportCsvBtn->setEnabled(hasRows);
}

// ========== 槽函数实现 ==========

void CollectorConfigDialog::onNameChanged(const QString& text) {
    Q_UNUSED(text);
}

void CollectorConfigDialog::onIpChanged(const QString& text) {
    Q_UNUSED(text);
}

void CollectorConfigDialog::onAddMapping() {
    // 创建默认映射规则
    CollectorMappingRule rule;
    rule.tagName = tr("NewTag%1").arg(m_mappings.size() + 1);  // 自动编号
    rule.registerType = RegisterType::HoldingRegister;
    rule.dataType = DataType::UInt16;
    rule.byteOrder = ByteOrder::AB;
    rule.scale = 1.0;
    rule.offset = 0.0;
    rule.enabled = true;
    
    // 智能地址递增：基于上一条映射的地址和数据类型
    if (!m_mappings.isEmpty()) {
        const CollectorMappingRule& lastRule = m_mappings.last();
        // 下一个地址 = 上一个地址 + 上一个数据类型占用的寄存器数
        int lastRegisterCount = DataTypeUtils::getRegisterCount(lastRule.dataType);
        rule.address = lastRule.address + lastRegisterCount;
    } else {
        rule.address = 0;  // 第一条从0开始
    }
    
    m_mappings.append(rule);
    refreshMappingTable();
    
    // 选中新添加的行
    m_mappingTable->selectRow(m_mappings.size() - 1);
    
    // 自动聚焦到标签名单元格（注意列索引改为1）
    m_mappingTable->editItem(m_mappingTable->item(m_mappings.size() - 1, 1));
}

void CollectorConfigDialog::onDeleteMapping() {
    int row = m_mappingTable->currentRow();
    if (row < 0 || row >= m_mappings.size()) {
        return;
    }
    
    m_mappings.removeAt(row);
    refreshMappingTable();
}

void CollectorConfigDialog::onDuplicateMapping() {
    int row = m_mappingTable->currentRow();
    if (row < 0 || row >= m_mappings.size()) {
        return;
    }
    
    // 复制当前行的映射规则
    CollectorMappingRule rule = getMappingRuleFromRow(row);
    
    // 智能命名：在原标签名后加序号
    rule.tagName = QString("%1_Copy%2").arg(rule.tagName).arg(m_mappings.size() + 1);
    
    // 智能地址递增：基于最后一条的地址
    if (!m_mappings.isEmpty()) {
        const CollectorMappingRule& lastRule = m_mappings.last();
        int lastRegisterCount = DataTypeUtils::getRegisterCount(lastRule.dataType);
        rule.address = lastRule.address + lastRegisterCount;
    }
    
    m_mappings.append(rule);
    refreshMappingTable();
    
    // 选中新复制的行
    m_mappingTable->selectRow(m_mappings.size() - 1);
}

void CollectorConfigDialog::onMappingTableSelectionChanged() {
    updateMappingButtons();
}

void CollectorConfigDialog::onMappingTableCellChanged(int row, int column) {
    if (m_isUpdatingTable) {
        return;
    }
    
    // 当单元格内容变化时，更新对应的映射规则
    if (row >= 0 && row < m_mappings.size()) {
        m_mappings[row] = getMappingRuleFromRow(row);
    }
}

void CollectorConfigDialog::onImportFromCSV() {
    // 创建菜单选择导入方式
    QMenu menu(this);
    QAction* importAction = menu.addAction(tr("导入CSV文件"));
    QAction* templateAction = menu.addAction(tr("下载CSV模板"));
    
    QAction* selectedAction = menu.exec(QCursor::pos());
    
    if (selectedAction == templateAction) {
        // 生成CSV模板
        QString fileName = QFileDialog::getSaveFileName(
            this,
            tr("保存CSV模板"),
            "collector_mapping_template.csv",
            tr("CSV文件 (*.csv)")
        );
        
        if (!fileName.isEmpty()) {
            if (CsvHelper::generateCollectorTemplate(fileName)) {
                QMessageBox::information(this, tr("成功"), 
                    tr("CSV模板已生成：\n%1\n\n请参考模板格式填写数据后导入。").arg(fileName));
            } else {
                QMessageBox::warning(this, tr("错误"), 
                    tr("无法生成CSV模板文件。"));
            }
        }
        return;
    }
    
    if (selectedAction == importAction) {
        // 导入CSV文件
        QString fileName = QFileDialog::getOpenFileName(
            this,
            tr("导入CSV文件"),
            "",
            tr("CSV文件 (*.csv)")
        );
        
        if (fileName.isEmpty()) {
            return;
        }
        
        // 询问是否清空现有数据
        QMessageBox::StandardButton reply = QMessageBox::question(
            this,
            tr("导入模式"),
            tr("是否清空现有映射规则？\n\n"
               "点击【是】：清空现有规则，只保留导入的数据\n"
               "点击【否】：追加导入的数据到现有规则"),
            QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel
        );
        
        if (reply == QMessageBox::Cancel) {
            return;
        }
        
        bool clearExisting = (reply == QMessageBox::Yes);
        
        // 导入CSV
        QList<CollectorMappingRule> importedMappings;
        QString errorMsg;
        
        if (!CsvHelper::importCollectorMappings(fileName, importedMappings, errorMsg)) {
            QMessageBox::critical(this, tr("导入失败"), 
                tr("无法导入CSV文件：\n%1").arg(errorMsg));
            return;
        }
        
        // 更新映射列表
        if (clearExisting) {
            m_mappings.clear();
        }
        
        m_mappings.append(importedMappings);
        
        // 刷新表格
        refreshMappingTable();
        
        QMessageBox::information(this, tr("导入成功"), 
            tr("成功导入 %1 条映射规则。").arg(importedMappings.size()));
    }
}

void CollectorConfigDialog::onExportToCSV() {
    if (m_mappings.isEmpty()) {
        QMessageBox::information(this, tr("提示"), 
            tr("当前没有映射规则可导出。"));
        return;
    }
    
    // 先同步表格数据到m_mappings
    for (int i = 0; i < m_mappingTable->rowCount(); ++i) {
        if (i < m_mappings.size()) {
            m_mappings[i] = getMappingRuleFromRow(i);
        }
    }
    
    QString fileName = QFileDialog::getSaveFileName(
        this,
        tr("导出到CSV"),
        QString("collector_mappings_%1.csv").arg(m_nameEdit->text()),
        tr("CSV文件 (*.csv)")
    );
    
    if (fileName.isEmpty()) {
        return;
    }
    
    if (CsvHelper::exportCollectorMappings(m_mappings, fileName)) {
        QMessageBox::information(this, tr("导出成功"), 
            tr("成功导出 %1 条映射规则到：\n%2").arg(m_mappings.size()).arg(fileName));
    } else {
        QMessageBox::critical(this, tr("导出失败"), 
            tr("无法导出CSV文件。"));
    }
}

void CollectorConfigDialog::onAccepted() {
    // 同步表格数据到m_mappings
    for (int i = 0; i < m_mappingTable->rowCount(); ++i) {
        if (i < m_mappings.size()) {
            m_mappings[i] = getMappingRuleFromRow(i);
        }
    }
    
    if (validateConfig()) {
        accept();
    }
}

void CollectorConfigDialog::onRejected() {
    reject();
}

} // namespace ModbusPlexLink

